#!/bin/bash

# ----------------------------------------------------------------------
# Filename:   chcon.sh
# Version:    1.0
# Date:       2013/12/18
# Author:     huijing.hei
# Email:      huijing.hei@cs2c.com.cn
# Summary:    03系统安全功能-01SELinux-03SELinux重要命令-03SELinux安全上下文标签相关命令-10chcon和restorecon
# Notes:       ***
# Copyright:    China Standard Software Co., Ltd.
# History：     
#             Version 1.0, 2013/12/18
#             - chcon, restorecon
# ----------------------------------------------------------------------

##! @TODO: enforcing
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure

function DoSetup()
{
    trap DoCleanup EXIT INT 

    IsRoot
    EchoResult "root"

    CmdCheck getenforce genhomedircon

    # check selinux status is enforcing or permissive
    CheckSElinuxStatus
    EchoResult "check selinux status is enforcing or permissive"

    # set selinux enforcing
    SELINUX_STA=`getenforce | tr A-Z a-z`
    SetSElinux enforcing
    EchoResult "set selinux enforcing"

    # ls --scontext
    VSFTPD_CONF=/etc/vsftpd/vsftpd.conf
    chcon -u system_u ${VSFTPD_CONF}
    ls --scontext ${VSFTPD_CONF} | grep "system_u:object_r:etc_t:s0"
    EchoResult "check ${VSFTPD_CONF} context"


}

##! @TODO: 
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure
function DoTest()
{
    # change context
    chcon -t tmp_t ${VSFTPD_CONF}

    ls --scontext ${VSFTPD_CONF} | grep "system_u:object_r:tmp_t:s0"
    EchoResult "chon tmp_t success"

    # change vsftpd.conf context refered to smb.conf
    SMB_CONF=/etc/samba/smb.conf
    ls --scontext ${SMB_CONF} | grep "system_u:object_r:samba_etc_t:s0"
    EchoResult "ls --scontext ${SMB_CONF}"

    chcon --reference=${SMB_CONF} ${VSFTPD_CONF}
    EchoResult "chon --reference"
    
    ls --scontext ${VSFTPD_CONF} | grep "system_u:object_r:samba_etc_t:s0"
    EchoResult "ls --scontext ${VSFTPD_CONF}"

    # restore context vsftpd.conf
    restorecon ${VSFTPD_CONF}
    ls --scontext ${VSFTPD_CONF} | grep "system_u:object_r:etc_t:s0"
    EchoResult "restore:  ${VSFTPD_CONF}"

}
##! @TODO: cleanup
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure

function DoCleanup()
{
    # restore selinux
    SetSElinux ${SELINUX_STA}
    EchoResult "restore selinux to ${SELINUX_STA}"

}

# include lib files

if [ -z "$SFROOT" ]
then
    echo "SFROOT is null, pls check"
    exit 1
fi

. ${SFROOT}/lib/Echo.sh
. ${SFROOT}/lib/Check.sh
. ${SFROOT}/lib/NetOps.sh
. ${SFROOT}/testcases/SELinux/lib/Selib.sh
. ${SFROOT}/testcases/SELinux/lib/UserOps.sh

export LANG=C

DoSetup
DoTest
EchoResult "testcase: selinux- chcon"
echo ""
